package com.ziq.baselib.business.post

import android.annotation.SuppressLint
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.ziq.baselib.business.post.bean.PostingDetail
import com.ziq.baselib.business.post.bean.PostingListParam
import com.ziq.baselib.business.post.bean.PostingListRespond
import dagger.hilt.android.lifecycle.HiltViewModel
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.schedulers.Schedulers
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import javax.inject.Inject

@HiltViewModel
class PostingListViewModel @Inject constructor() : ViewModel() {

    init {
        println("PostingListViewModel constructor")
    }

    @Inject
    lateinit var postingService: PostingService

    val listRequestFinished = MutableLiveData<Boolean>()
    val listHasMore = MutableLiveData<Boolean>()
    val list = MutableLiveData<MutableList<PostingDetail>>()

    var page = 1
    var pageSize = 20

    fun onRefresh(){
        page = 1
        requestList()
    }

    fun onLoadMore(){
        requestList()
    }

    @SuppressLint("CheckResult")
    fun requestList(
        onSuccess: ((result: PostingListRespond) -> Unit)? = {
            if (it.data != null){
                val tempList = mutableListOf<PostingDetail>()
                if(page != 1 && list.value != null){
                    tempList.addAll(list.value!!)
                }
                if(it.data?.list?.isNotEmpty() == true){
                    tempList.addAll(it.data!!.list!!)
                }
                list.postValue(tempList)

                page++
                if(it.data?.has_more == true){
                    listHasMore.postValue(true)
                } else {
                    listHasMore.postValue(false)
                }
            }else {
                listHasMore.postValue(false)
            }
            listRequestFinished.postValue(true)
        },
        onFail: (() -> Unit)? = {
            listRequestFinished.postValue(true)
        }) {

        val param = PostingListParam()
        param.page = page
        param.size = pageSize
        postingService.listRepos(param)
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(
                {
                    if(it != null){
                        onSuccess?.invoke(it)
                    } else {
                        onFail?.invoke()
                    }

                },{
                    onFail?.invoke()
                }
            )
    }

    fun testViewModelScope(){
        println("testViewModelScope 1 -- ${Thread.currentThread().name}")
        viewModelScope.launch(Dispatchers.Default){
            println("testViewModelScope 2 -- ${Thread.currentThread().name}")
        }
    }

}